<template>
    <s-layout title="订单详情">
        <view class="detail-container" v-if="state.order.id">
            <uni-card>
                <template #title>
                    <view class="card-header">
                        <text>订单信息</text>
                        <text :class="`order-status ${formatOrderStatusColor(state.order.orderStatus)}`">{{ formatOrderStatus(state.order.orderStatus) }}</text>
                    </view>
                </template>
                <view class="detail-item">
                    <text class="label">订单编号:</text>
                    <text class="value">{{ state.order.orderCode }}</text>
                </view>
                <view class="detail-item">
                    <text class="label">创建时间:</text>
                    <text class="value">{{ formatDate(state.order.createTime) }}</text>
                </view>
                <view class="detail-item">
                    <text class="label">产品名称:</text>
                    <text class="value">{{ state.order.productName }}</text>  <!-- 需要转换 -->
                </view>
                <view class="detail-item">
                    <text class="label">代理商:</text>
                    <text class="value phone" @tap="callPhone(agentInfo.mobile)">{{ state.order.agentName }}</text> <!-- 需要转换 -->
                </view>
              <view class="detail-item" v-if="state.order.orderStatus !=='PENDING_REVIEW'">
                <text class="label">生产方:</text>
                <text class="value phone" @tap="callPhone(getProducerName(state.order.manufacturerId,'phone'))">{{ getProducerName(state.order.manufacturerId,'name') }}</text> <!-- 需要转换 -->
              </view>
                <view class="detail-item select-top" v-else>
                    <text class="label">生产方:</text>
                    <uni-data-select
                        v-model="state.order.manufacturerId"
                        :localdata="state.producerList"
                        placement="top"
                        placeholder="请选择生产方"
                    />
                </view>

            </uni-card>

            <uni-card title="详细信息" :is-shadow="false">
                <view class="detail-item"><text class="label">细胞规格:</text><text class="value">{{ state.order.cellSpecification }}</text></view>
                <view class="detail-item"><text class="label">是否拆分:</text><text class="value">{{ state.order.isSplit ? '是' : '否' }}</text></view>
                <view class="detail-item"><text class="label">袋(管)数:</text><text class="value">{{ state.order.bagCount }}</text></view>
                <view class="detail-item"><text class="label">细胞总数:</text><text class="value">{{ state.order.totalCells }}</text></view>
                <view class="detail-item"><text class="label">细胞来源:</text><text class="value">{{state.order.cellOrigin=='ALLOGENEIC'?'不指定':'自体'}}</text></view>
                <view class="detail-item"><text class="label">来源备注:</text><text class="value">{{ state.order.originRemark || '-' }}</text></view>
                <view class="detail-item"><text class="label">使用时间:</text><text class="value">{{ formatDate(state.order.usageTime) }}</text></view>
                <view class="detail-item"><text class="label">预约数量:</text><text class="value">{{ state.order.reservationQuantity }}</text></view>
                <view class="detail-item"><text class="label">订单备注:</text><text class="value">{{ state.order.remark }}</text></view>
            </uni-card>

            <uni-card title="使用与签收信息" :is-shadow="false">
                <view class="detail-item"><text class="label">使用人:</text><text class="value">{{ state.order.userName || '-' }}</text></view>
                <view class="detail-item"><text class="label">联系方式:</text><text class="value phone" @tap="callPhone(state.order.userContact)">{{ state.order.userContact || '-' }}</text></view>
                <view class="detail-item"><text class="label">签收人:</text><text class="value">{{ state.order.signerName || '-' }}</text></view>
                <view class="detail-item"><text class="label">签收人手机:</text><text class="value phone" @tap="callPhone(state.order.signerContact)">{{ state.order.signerContact || '-' }}</text></view>
            </uni-card>

            <uni-card title="审核与生产信息" :is-shadow="false" v-if="state.order.auditTime || state.order.productionStartTime">
                <view class="detail-item" v-if="state.order.auditTime"><text class="label">审核时间:</text><text class="value">{{ formatDate(state.order.auditTime) }}</text></view>
                <view class="detail-item" v-if="state.order.auditor"><text class="label">审核人:</text><text class="value">{{ state.order.auditorName }}</text></view>
                <view class="detail-item" v-if="state.order.rejectReason && state.order.orderStatus=='REJECTED'"><text class="label">驳回原因:</text><text class="value">{{ state.order.rejectReason }}</text></view>
                <view class="detail-item" v-if="state.order.productionStartTime"><text class="label">开始生产时间:</text><text class="value">{{ formatDate(state.order.productionStartTime) }}</text></view>
                <view class="detail-item" v-if="state.order.productionEndTime"><text class="label">完成生产时间:</text><text class="value">{{ formatDate(state.order.productionEndTime) }}</text></view>
            </uni-card>

            <uni-card title="提货信息" :is-shadow="false" v-if="state.order.pickupTime">
                <view class="detail-item"><text class="label">提货时间:</text><text class="value">{{ formatDate(state.order.pickupTime) }}</text></view>
                <view class="detail-item"><text class="label">提货备注:</text><text class="value">{{ state.order.pickupRemark || '-' }}</text></view>
                <view class="detail-item" v-if="state.order.pickupPhotos && state.order.pickupPhotos.length">
                    <text class="label">提货照片:</text>
                    <view class="image-list">
                        <image v-for="(photo, index) in state.order.pickupPhotos" :key="index" :src="photo" mode="aspectFill" class="pickup-image" @tap="previewImage(index)"></image>
                    </view>
                </view>
            </uni-card>

            <uni-card title="代理商信息" :is-shadow="false" >
                <view class="detail-item"><text class="label">总订单数量:</text><text class="value">{{ agentInfo.orderCount }}</text></view>
                <view class="detail-item"><text class="label">总订单金额:</text><text class="value">{{ agentInfo.orderAmount }}</text></view>
                <view class="detail-item"><text class="label">代理商名称:</text><text class="value">{{ agentInfo.userName }}</text></view>
                <view class="detail-item"><text class="label">代理商电话:</text><text class="value phone" @tap="callPhone(agentInfo.mobile)">{{ agentInfo.mobile}}</text></view>
                <view class="detail-item"><text class="label">代理商备注:</text><text class="value">{{agentInfo.remark}}</text></view>
            </uni-card>

            <!-- 审核按钮区域 -->
            <view class="audit-buttons" v-if="state.order.orderStatus=='PENDING_REVIEW'">
                <button
                        class="audit-btn ui-BG-Main-Gradient"
                        @click="handleApprove"
                        :disabled="state.loading"
                >
                    {{ state.loading && state.actionType === 'approve' ? '处理中...' : '审核通过' }}
                </button>
                <button
                        class="audit-btn reject-btn"
                        @click="handleReject"
                        :disabled="state.loading"
                >
                    {{ state.loading && state.actionType === 'reject' ? '处理中...' : '驳回' }}
                </button>
            </view>

        </view>
        <s-empty v-else text="订单加载中..." />

        <!-- 审核弹窗 -->
        <uni-popup ref="approvePopup" type="dialog">
            <uni-popup-dialog
                mode="input"
                title="审核订单"
                placeholder="请输入订单总金额"
                :value="state.approveAmount"
                @input="value => state.approveAmount = value"
                @confirm="confirmApprove"
                @close="cancelApprove"
            >
                <template #default>
                    <view class="approve-dialog">
                        <input
                            v-model="state.approveAmount"
                            type="number"
                            class="approve-input"
                            placeholder="请输入订单总金额"
                        />
                    </view>
                </template>
            </uni-popup-dialog>
        </uni-popup>


        <!-- 驳回原因输入弹窗 -->
        <uni-popup ref="rejectPopup" type="dialog">
            <uni-popup-dialog
                    mode="input"
                    title="驳回订单"
                    placeholder="请输入驳回原因"
                    :value="state.rejectReason"
                    @input="handleRejectReasonInput"
                    @confirm="confirmReject"
                    @close="cancelReject"
            >
                <template #default>
                    <view class="reject-dialog">
                        <textarea
                                class="reject-textarea"
                                v-model="state.rejectReason"
                                placeholder="请详细说明驳回原因..."
                                maxlength="200"
                                :show-confirm-bar="false"
                        />
                        <view class="char-count">{{ state.rejectReason.length }}/200</view>
                    </view>
                </template>
            </uni-popup-dialog>
        </uni-popup>
    </s-layout>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import { formatDate } from '@/sheep/helper/utils';
import ReservationRecordApi from '@/sheep/api/system/reservationRecord';
import SLayout from '@/sheep/components/s-layout/s-layout.vue';
import SEmpty from '@/sheep/components/s-empty/s-empty.vue';
import UniCard from '@/uni_modules/uni-card/components/uni-card/uni-card.vue';
import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
import UniPopupDialog from '@/uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue';
import AgentApi from "@/sheep/api/agent/agent";

// 订单状态枚举
const ORDER_STATUS = {
    PENDING_REVIEW: '待审核',
    PENDING_PROD: '待生产',
    PRODUCING: '生产中',
    PRODUCED: '待提货',
    PICKED_UP: '已完成',
    REJECTED: '已驳回'
};

const state = reactive({
    order: {},
    approveAmount:'',
    orderId: null,
    loading: false,
    actionType: '', // 'approve' 或 'reject'
    rejectReason: ''
});

const agentInfo = ref({});
const rejectPopup = ref(null);

const formatOrderStatus = (status) => ORDER_STATUS[status] || '未知';
const formatOrderStatusColor = (status) => {
    const colorMap = {
        PENDING_REVIEW: 'warning-color',
        PENDING_PROD: 'warning-color',
        PRODUCING: 'primary-color', // 假设有主要颜色
        PRODUCED: 'success-color',
        PICKED_UP: 'success-color',
        REJECTED: 'danger-color'
    };
    return colorMap[status] || 'primary-color';
};

// 拨打电话方法
const callPhone = (phoneNumber) => {
  if (!phoneNumber) {
    uni.showToast({
      title: '暂无联系电话',
      icon: 'none'
    })
    return
  }

  uni.makePhoneCall({
    phoneNumber,
    success: () => {
      console.log('拨打成功')
    },
    fail: (err) => {
      console.error('拨打失败', err)
    }
  })
}
const getProducerName = (id,type) => {
  const producer = state.producerList.find(item => item.value === id)
  if (type === 'name') {
    return producer ? producer.text : '未知生产方'
  }else if (type === 'phone') {
    return producer ? producer.phone : '-'
  }
}


async function getOrderDetail() {
    try {
        const { code, data } = await ReservationRecordApi.getDetail({id:state.orderId});
        if (code === 0) {
            state.order = data;
            const dataAgent = await AgentApi.getAgent({id:data.agentId})
            agentInfo.value = dataAgent.data
        } else {
            sheep.$helper.toast('获取订单详情失败');
        }
    } catch (e) {
        console.error(e);
    }
}
const approvePopup = ref(null);
state.approveAmount = ''; // 审核通过时输入的订单总金额

// 审核通过处理
const handleApprove = () => {
    if(!state.order.manufacturerId) {
        sheep.$helper.toast('请选择生产方');
        return;
    }else{
      const exists = state.producerList.some(
        item => item.value === state.order.manufacturerId
      )
      if (!exists) {
        sheep.$helper.toast('请选择生产方');
        return;
      }
    }
    state.approveAmount = '';
    approvePopup.value.open();
};

const confirmApprove = async () => {
    if (!state.approveAmount || Number(state.approveAmount) <= 0) {
        sheep.$helper.toast('请输入有效的订单总金额');
        return;
    }

    try {
        state.loading = true;
        state.actionType = 'approve';

        state.order.orderStatus = 'PENDING_PROD';
        state.order.orderAmount = Number(state.approveAmount); // 假设 API 接收 totalAmount 字段

        const { code, msg } = await ReservationRecordApi.audit(state.order);

        if (code === 0) {
            uni.showToast({
                title: '审核通过成功',
                icon: 'success'
            })
            setTimeout(() => {
                approvePopup.value.close();
                getOrderDetail();
            }, 800)
        } else {
            sheep.$helper.toast(msg || '审核失败');
        }
    } catch (error) {
        console.error('审核通过失败:', error);
        sheep.$helper.toast('审核失败，请重试');
    } finally {
        state.loading = false;
        state.actionType = '';
    }
};

const cancelApprove = () => {
    state.approveAmount = '';
    approvePopup.value.close();
};



// 驳回处理
const handleReject = () => {
    state.rejectReason = '';
    rejectPopup.value.open();
};

// 驳回原因输入处理
const handleRejectReasonInput = (value) => {
    state.rejectReason = value;
};

// 确认驳回
const confirmReject = async () => {
    if (!state.rejectReason.trim()) {
        sheep.$helper.toast('请输入驳回原因');
        return;
    }

    try {
        state.loading = true;
        state.actionType = 'reject';

        state.order.orderStatus = 'REJECTED'
        state.order.rejectReason = state.rejectReason.trim()
        // 调用驳回API - 根据实际API调整参数
        const { code, msg } = await ReservationRecordApi.audit(state.order);

        if (code === 0) {
            uni.showToast({
                title: '驳回成功',
                icon: 'success'
            })
            setTimeout(() => {
                rejectPopup.value.close();
                // 刷新订单详情
                 getOrderDetail();
            }, 800)

        } else {
            sheep.$helper.toast(msg || '驳回失败');
        }
    } catch (error) {
        console.error('驳回失败:', error);
        sheep.$helper.toast('驳回失败，请重试');
    } finally {
        state.loading = false;
        state.actionType = '';
    }
};

// 取消驳回
const cancelReject = () => {
    state.rejectReason = '';
    rejectPopup.value.close();
};

const goToEdit = () => {
    sheep.$router.go('/pages/order/edit', { id: state.orderId });
}

const previewImage = (index) => {
    uni.previewImage({ urls: state.order.pickupPhotos, current: index });
};
async function getProducerList() {
    try {
        let {
            code,
            data
        } = await AgentApi.getProduceList({});
        if (code === 0 && data) {
          // 假设 state.producerList 已经有原数据
          state.producerList =  data.map(item => ({
              value: item.id,      // 使用 id 作为 value
              text: item.userName,  // 使用 userName 作为 text
              phone: item.mobile
            }))
        }
    } catch (error) {
        console.error('获取生产方列表失败:', error);
    }
}

onLoad((options) => {
    if (options.id) {
        state.orderId = options.id;
        getOrderDetail();
    }
    getProducerList()
});
</script>

<style lang="scss" >
/* 通用宽度设置 */
.detail-item uni-data-select {
    width: 300rpx;
}
.phone {
  color: #007aff !important;
  text-decoration: underline;
}
.detail-container { padding: 0rpx;
    padding-bottom: 120rpx; /* 留出底部按钮的空间 */
    box-sizing: border-box;
}
.card-header { display: flex; justify-content: space-between;
  padding-top: 20rpx;
  align-items: center; font-size: 30rpx; font-weight: 500; }
.order-status { font-size: 26rpx; font-weight: normal; }
.detail-item { display: flex; justify-content: space-between; padding: 20rpx 0; font-size: 28rpx; border-bottom: 1rpx solid #f5f5f5;
  .label { color: #666; }
  .value { color: #333; text-align: right; }
}
.detail-item:last-child { border-bottom: none; }
.image-list { display: flex; flex-wrap: wrap; margin-top: 10rpx; justify-content: flex-end; }
.pickup-image { width: 120rpx; height: 120rpx; margin-left: 10rpx; margin-bottom: 10rpx; border-radius: 8rpx; }
.action-btn { width: 90%; height: 80rpx; border-radius: 40rpx; font-size: 30rpx; background-color: #f0f0f0; color: #333; }

.warning-color { color: #faad14; }
.danger-color { color: #ff3000; }
.info-color { color: #999999; }
.primary-color { color: #007aff; }
.success-color { color: #52c41a; }

/* 审核按钮样式 */
.audit-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    gap: 20rpx;
    padding: 20rpx 20rpx;
    justify-content: center;
    background: #fff;
    z-index: 99;
    box-shadow: 0 -4rpx 8rpx rgba(0,0,0,0.05);
}

.audit-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  transition: all 0.3s ease;

  &:disabled {
    opacity: 0.6;
  }
}

.approve-btn {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

  &:active:not(:disabled) {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.4);
  }
}

.reject-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);

  &:active:not(:disabled) {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.4);
  }
}

/* 驳回弹窗样式 */
.reject-dialog {
  padding: 40rpx;
}

.reject-title {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 24rpx;
}

.reject-textarea {
  width: 400rpx;
  min-height: 200rpx;
  padding: 20rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 12rpx;
  font-size: 28rpx;
  line-height: 1.5;
  resize: none;
  box-sizing: border-box;

  &:focus {
    border-color: #1890ff;
    outline: none;
  }
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
  margin-bottom: 40rpx;
}

.dialog-buttons {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}

.dialog-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: 500;
  border: none;

  &:disabled {
    opacity: 0.6;
  }
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;

  &:active:not(:disabled) {
    background-color: #e8e8e8;
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  color: #ffffff;

  &:active:not(:disabled) {
    transform: translateY(1rpx);
  }
}
</style>
